package com.wangyf.thread.c_008_unsafe;

import org.openjdk.jol.info.ClassLayout;
import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Java8获取Unsafe实例的正确方式
 * 参考: https://blog.csdn.net/doegoo/article/details/89514070?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control
 *
 * @author wangyf
 * @date 2021/1/2 17:46
 */
public class TT {
    private static final Unsafe THE_UNSAFE;
    static{
        try {
            final PrivilegedExceptionAction<Unsafe> action = new PrivilegedExceptionAction<Unsafe>() {
                public Unsafe run() throws Exception {
                    Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
                    theUnsafe.setAccessible(true);
                    return (Unsafe) theUnsafe.get(null);
                }
            };
            THE_UNSAFE = AccessController.doPrivileged(action);
        }
        catch (Exception e){
            throw new RuntimeException("Unable to load unsafe", e);
        }
    }

    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        Unsafe unsafe = THE_UNSAFE;
        boolean b = unsafe.compareAndSwapInt(atomicInteger, 12, 0, 1);
        // 还是这个好用 直接看偏移量是多少
        //System.out.println(ClassLayout.parseInstance(atomicInteger).toPrintable(atomicInteger));
        System.out.println(b);
        System.out.println(atomicInteger);
    }
}
